﻿using System.Linq;
using Microsoft.International.Converters.PinYinConverter;

namespace ESoft.Helpers {

    /// <summary>
    /// 拼音辅助类
    /// </summary>
    public static class PinyinHelper {

        /// <summary>
        /// 获取首字母
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static char GetFirstChar(string name) {
            var c = name.First();
            if (('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z')) {
                return c;
            }

            try {
                var cc = new ChineseChar(c);
                if (cc.Pinyins.Count > 0 && cc.Pinyins[0].Length > 0) {
                    return cc.Pinyins[0][0];
                }
            }
            catch {
                return c;
            }
            return c;
        }

        /// <summary>
        /// 获得中文字符串的拼音
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetPinYinStr(string str) {
            string py = "";

            for (int i = 0; i < str.Length; i++) {
                //判断当前字符是不是汉字
                if (ChineseChar.IsValidChar(str[i])) {
                    var cc = new ChineseChar(str[i]);//构造方法             
                    py += cc.Pinyins[0].TrimEnd('1', '2', '3', '4', '5').ToLower();
                }
                else//不是汉字的话 加本身
                {
                    py += str[i];
                }

            }

            return py;
        }
    }
}